package com.zang.util;

import com.zang.constants.IEnum;
import lombok.extern.slf4j.Slf4j;

/**
 * 枚举转换
 *
 * @author gs
 * @date 2022/6/9 8:05 PM
 */
@Slf4j
public class EnumUtils<E extends Enum<?> & IEnum<Integer>> {

    private final Class<E> clazz;

    public EnumUtils(Class<E> enumType) {
        if (enumType == null)
            throw new IllegalArgumentException("Type argument cannot be null");
        this.clazz = enumType;
    }

    /**
     * 转换type为enum类
     * 需要继承IEnum
     * @param columnIndex value值
     * @return enum类
     * @throws NullPointerException
     */
    public E getNullableResult(int columnIndex) {
        try {
            return codeOf(clazz, columnIndex);
        } catch (Exception e){
            log.error(e.getMessage());
            throw e;
        }
    }

    public static <E extends Enum<?> & IEnum<Integer>> E codeOf(Class<E> enumClass, int value) {
        E[] enumConstants = enumClass.getEnumConstants();
        for (E e : enumConstants) {
            if (e.getValue() == value)
                return e;
        }
        return null;
    }
}
